package com.notes.config.date;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @author: huxingxin
 * @date: 2024/12/26
 * 在处理 HTTP 请求参数为表单数据时，给数据绑定过程中指定日期时间的格式
 * 支持的数据格式：localDateTime, LocalDate, Date
 */
@Configuration
public class DateBindConfig {
    private final String datePattern="yyyy-MM-dd";
    private final String dateTimePattern = "yyyy-MM-dd HH:mm:ss";

    private final DateTimeFormatter dateTimeformatter = DateTimeFormatter.ofPattern(dateTimePattern);
    private final DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(datePattern);
    private final SimpleDateFormat sdf = new SimpleDateFormat(dateTimePattern);

    private final boolean lenient = false;

    /**
     * 全局的日期转换器 Date
     * @return
     */
    @Bean
    public Converter<String, Date> dateConvert() {
        return new Converter<String, Date>() {
            @Override
            public Date convert(String source) {
                sdf.setLenient(lenient);
                Date dateTime;
                try {
                    dateTime = sdf.parse(source);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
                return dateTime;
            }
        };
    }

    /**
     * 全局的日期转换器 LocalDateTime
     * @return
     */
    @Bean
    public Converter<String, LocalDateTime> localDateTimeConvert() {
        return new Converter<String, LocalDateTime>() {
            @Override
            public LocalDateTime convert(String source) {
                return LocalDateTime.parse(source, dateTimeformatter);
            }
        };
    }

    /**
     * 全局的日期转换器 LocalDate
     * @return
     */
    @Bean
    public Converter<String, LocalDate> localDateConvert() {
        return new Converter<String, LocalDate>() {
            @Override
            public LocalDate convert(String source) {
                return LocalDate.parse(source, dateFormatter);
            }
        };
    }
}
